// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-04-16 10:34
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DateTrain;

import org.junit.jupiter.api.Test;

/**
 * 最大位数回文数：枚举 + 判断回文
 */
public class LargestPalindrome {
    public int largestPalindromeT(int n) {
        int top = (int) Math.pow(10, n) - 1;
        int bot = (int) Math.pow(10, n - 1);
        int max = 0;
        for (int i = top; i >= bot; i--) {
            for (int j = i; j >= bot; j--) {
                if (isPalindrome(i * j)) {
                    max = Math.max(max, i * j);
                }
            }
        }
        return max % 1337;
    }

    /**
     * 判断出入的字符串是否是回文字符串
     */
    private boolean isPalindrome(int num) {
        String s = num + "";
        int n = s.length();
        int l = 0, r = n - 1;
        char[] chars = s.toCharArray();
        while (l < r) {
            if (chars[l] != chars[r]) {
                return false;
            }
            l++;
            r--;
        }
        return true;
    }


    public int largestPalindrome(int n) {
        if (n == 1) {
            return 9;
        }
        int max = (int) Math.pow(10, n) - 1;
        int bot = (int) Math.pow(10, n - 1);
        for (int i = max; i >= bot; i--) {
            long num = i, t = i;
            while (t != 0) {
                // 翻转自身到末尾构造回文数
                num = num * 10 + (t % 10);
                t /= 10;
            }
            for (long j = max; j * j >= num; j--) {
                // 从大到小进行枚举，第一个合法值就是需要的回文字符串
                if (num % j == 0) {
                    return (int) (num % 1337);
                }
            }
        }
        return -1;
    }


    @Test
    public void shout() {
        System.out.println(largestPalindrome(6));
    }
}
